package controller

import (
	"admin/contrib/session"
	"admin/contrib/validator"
	"admin/model"
	"common/helper"
	"encoding/json"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"go.mongodb.org/mongo-driver/bson"
	"strings"
	"unicode/utf8"
)

type MessageController struct{}

type messageInsertParam struct {
	Title    string `json:"title"`     //标题
	Content  string `json:"content"`   //内容
	Ty       int    `json:"ty"`        //1站内消息 2活动消息
	IsTop    int    `json:"is_top"`    //1不置顶 2置顶
	IsPush   int    `json:"is_push"`   //1不推送 2推送
	SendName string `json:"send_name"` //发送人名
	SendAt   string `json:"send_at"`   //发送时间
	IsVip    int    `json:"is_vip"`    //是否vip站内信 1 vip站内信 2 直属下级 3 全部下级
	Level    string `json:"level"`     //vip等级 0-10,多个逗号分割
	Names    string `json:"names"`     //会员名，多个用逗号分割
}

type messageListParam struct {
	Page            int    `json:"page"`
	PageSize        int    `json:"page_size"`
	Flag            int    `json:"flag"`              //1审核列表 2历史记录
	Title           string `json:"title"`             //标题
	SendName        string `json:"send_name"`         //发送人
	IsVip           int    `json:"is_vip"`            //是否vip站内信 1 vip站内信 2 直属下级 3 全部下级
	IsPush          int    `json:"is_push"`           //1不推送 2推送
	Ty              int    `json:"ty"`                //1站内消息 2活动消息
	SendStartTime   string `json:"send_start_time"`   //发送开始时间
	SendEndTime     string `json:"send_end_time"`     //发送结束时间
	StartTime       string `json:"start_time"`        //申请开始时间
	EndTime         string `json:"end_time"`          //申请结束时间
	ReviewStartTime string `json:"review_start_time"` //审核开始时间
	ReviewEndTime   string `json:"review_end_time"`   //审核结束时间
}

type messageUpdateParam struct {
	Id       string `json:"id"`
	Title    string `json:"title"`     //标题
	Content  string `json:"content"`   //内容
	IsTop    int    `json:"is_top"`    //1不置顶 2置顶
	SendName string `json:"send_name"` //发送人名
	SendAt   string `json:"send_at"`   //发送时间
}

type messageSystemParam struct {
	Page      int    `json:"page"`
	PageSize  int    `json:"page_size"`
	StartTime string `json:"start_time"`
	EndTime   string `json:"end_time"`
	Username  string `json:"username"`
	Title     string `json:"title"`
}
type messageDeleteParam struct {
	Id  string `json:"id"`
	Ids string `json:"ids"`
}

// 站内信新增
func (that *MessageController) Insert(ctx *fasthttp.RequestCtx) {

	data := messageInsertParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &data)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	if utf8.RuneCountInString(data.Title) < 1 || utf8.RuneCountInString(data.Title) > 255 ||
		//len(subTitle) < 1 || len(subTitle) > 255 ||
		utf8.RuneCountInString(data.Content) == 0 ||
		utf8.RuneCountInString(data.SendName) < 1 || utf8.RuneCountInString(data.SendName) > 100 {

		helper.RetData(ctx, false, helper.ContentLengthErr)
		return
	}

	if data.Ty != 1 && data.Ty != 2 || data.IsVip > 3 {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	switch data.IsVip {
	case 0:
		if data.Names == "" {
			helper.RetData(ctx, false, helper.UsernameErr)
			return
		}

		data.Names = strings.ToLower(data.Names)
		usernames := strings.Split(data.Names, ",")
		for _, v := range usernames {
			if !validator.CheckUName(v, 5, 14) {
				helper.RetData(ctx, false, helper.UsernameErr)
				return
			}
		}
	case 1:
		if data.Level == "" {
			helper.RetData(ctx, false, "参数错误")
			return
		}

	case 2, 3:
		data.Names = strings.ToLower(data.Names)
		if !validator.CheckUName(data.Names, 5, 14) {
			helper.RetData(ctx, false, helper.UsernameErr)
			return
		}
	default:
		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)

	record := g.Record{
		"id":          helper.GenId(),
		"title":       data.Title,        //标题
		"content":     data.Content,      //内容
		"is_top":      data.IsTop,        //1不置顶 2置顶
		"is_push":     data.IsPush,       //1不推送 2推送
		"is_vip":      data.IsVip,        //是否是vip
		"level":       data.Level,        //会员等级
		"ty":          data.Ty,           //站内信类型
		"usernames":   data.Names,        //会员名
		"state":       1,                 //1审核中 2审核通过 3审核拒绝 4已删除
		"send_state":  1,                 //1未发送 2已发送
		"send_name":   data.SendName,     //发送人名
		"apply_at":    ctx.Time().Unix(), //创建时间
		"apply_uid":   admin["id"],       //创建人uid
		"apply_name":  admin["name"],     //创建人名
		"review_at":   0,                 //审核时间
		"review_uid":  0,                 //审核人uid
		"review_name": "",                //审核人名
	}
	err = model.MessageInsert(record, data.SendAt)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// 站内信列表
func (that *MessageController) List(ctx *fasthttp.RequestCtx) {

	param := messageListParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	ex := g.Ex{}
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize < 10 {
		param.PageSize = 10
	}

	if param.Flag != 1 && param.Flag != 2 {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.Flag == 1 {
		ex["state"] = 1
	} else {
		ex["state"] = []int{2, 3, 4}
	}

	if param.Title != "" {
		ex["title"] = param.Title
	}

	if param.SendName != "" {
		ex["send_name"] = param.SendName
	}

	if param.Ty > 0 {
		if param.Ty != 1 && param.Ty != 2 {
			helper.RetData(ctx, false, "参数错误")
			return
		}

		ex["ty"] = param.Ty
	}

	if param.IsVip != 0 {
		if param.IsVip != 0 && param.IsVip != 0 {
			helper.RetData(ctx, false, "参数错误")
			return
		}

		ex["is_vip"] = param.IsVip
	}

	if param.IsPush != 0 {
		if param.IsPush != 0 && param.IsPush != 1 {
			helper.RetData(ctx, false, "参数错误")
			return
		}

		ex["is_push"] = param.IsPush
	}

	data, err := model.MessageList(param.Page, param.PageSize, param.SendStartTime, param.SendEndTime, param.StartTime, param.EndTime, param.ReviewStartTime, param.ReviewEndTime, ex)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

// 站内信编辑
func (that *MessageController) Update(ctx *fasthttp.RequestCtx) {

	param := messageUpdateParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	record := g.Record{}
	if !validator.CtypeDigit(param.Id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	if param.Title != "" {
		record["title"] = param.Title
	}

	if param.Content != "" {
		record["content"] = param.Content
	}

	if param.IsTop != 0 {
		if param.IsTop != 1 && param.IsTop != 2 {
			helper.RetData(ctx, false, "参数错误")
			return
		}

		record["is_top"] = param.IsTop
	}

	if param.SendName != "" {
		record["send_name"] = param.SendName
	}
	err = model.MessageUpdate(param.Id, param.SendAt, record)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

type messageReviewParam struct {
	Id    string `json:"id"`
	State int    `json:"state"`
	Flag  int    `json:"flag"` // 1 定时发送 2立即发送
}

// 站内信编辑
func (that *MessageController) Review(ctx *fasthttp.RequestCtx) {

	param := messageReviewParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	if !validator.CtypeDigit(param.Id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	flags := map[int]bool{
		1: true,
		2: true,
	}
	if _, ok := flags[param.Flag]; !ok {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	states := map[int]bool{
		2: true,
		3: true,
	}
	if _, ok := states[param.State]; !ok {
		helper.RetData(ctx, false, "状态错误")
		return
	}

	admin := session.AdminGet(ctx)

	err = model.MessageReview(param.Id, param.State, param.Flag, admin)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// 已发站内信详情
func (that *MessageController) Detail(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	id := string(ctx.QueryArgs().Peek("id"))

	if !validator.CtypeDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	if page == 0 {
		page = 1
	}
	if pageSize < 10 {
		pageSize = 10
	}
	data, err := model.MessageDetail(id, page, pageSize)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

// 已发系统站内信站内信列表
func (that *MessageController) System(ctx *fasthttp.RequestCtx) {

	param := messageSystemParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize < 10 {
		param.PageSize = 10
	}
	ex := bson.M{}

	if param.Username != "" {
		param.Username = strings.ToLower(param.Username)

		ex["username"] = param.Username
	}
	if param.Title != "" {
		ex["title"] = param.Title
	}
	data, err := model.MessageSystemList(param.StartTime, param.EndTime, param.Page, param.PageSize, ex)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

// 站内信删除
func (that *MessageController) Delete(ctx *fasthttp.RequestCtx) {

	param := messageDeleteParam{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Id == "" && param.Ids == "" {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	err = model.MessageDelete(param.Id, param.Ids)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}
